import Core from "../Core";

const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu("通用组件/MsgHints")
export default class MsgHints extends cc.Component {
  private _tween: cc.Tween | null = null; // 保存当前 tween 引用

  setMsg(str: string, holdtime: number) {
    const label = this.node.getComponentInChildren(cc.Label);
    if (label) label.string = str;

    // 立即重置状态（关键！）
    this.node.setScale(cc.v3(0, 0, 0));
    this.node.setPosition(cc.v3(0, 0, 0));
    this.node.y = cc.winSize.height * 0.3;

    // 中断之前的 tween（防止动画冲突）
    if (this._tween) {
      this._tween.stop();
      this._tween = null;
    }

    // 重新开始完整动画
    this._tween = cc
      .tween(this.node)
      .to(0.1, { scale: 1.1 })
      .to(0.1, { scale: 0.9 })
      .to(0.1, { scale: 1 })
      .delay(0.5 + holdtime)
      //.by(0.5, { y: 100 })
      .to(0.1, { scale: 1.1 })
      .to(0.1, { scale: 0.9 })
      .to(0.1, { scale: 0 })
      .call(() => {
        if (cc.isValid(this.node)) {
          this.node.active = false; // 不 destroy，留着复用
        }
        this._tween = null;
      })
      .start();
  }

  // ----------------------------
  // 单例管理
  // ----------------------------

  private static _instance: MsgHints | null = null;

  public static async show(msg: string, holdtime: number = 0) {
    // 第一次调用时创建实例
    if (!MsgHints._instance || !cc.isValid(MsgHints._instance.node)) {
      const prefab = (await Core.resHelper.load(
        "common/MsgHints",
        cc.Prefab,
        "prefabs"
      )) as cc.Prefab;

      const node = cc.instantiate(prefab);
      node.parent = Core.windowManager.container;
      node.zIndex = 9999;
      node.active = true;

      const comp = node.getComponent(MsgHints) || node.addComponent(MsgHints);
      MsgHints._instance = comp;
    }

    // 显示并播放动画
    MsgHints._instance.node.active = true;
    MsgHints._instance.setMsg(msg, holdtime);
  }
}
